<template>
  <div class="app-container">
    <el-form
      label-position="top"
      v-show="state.showSearch"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
    >
      <el-form-item label="公司名称" prop="companyId">
        <ApiSelect
          class="form-input"
          v-model="queryParams.companyId"
          :options="companyOptions"
          valueField="companyId"
          labelField="name"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderSn">
        <el-input class="form-input" v-model="queryParams.orderSn" placeholder="订单编号" />
      </el-form-item>
      <el-form-item label="设备编号" prop="machineId">
        <el-input class="form-input" v-model="queryParams.machineId" placeholder="设备编号" />
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select class="form-input" v-model="queryParams.payType" placeholder="请选择" clearable>
          <el-option
            v-for="dict in order_paytype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="payStatus">
        <el-select
          class="form-input"
          v-model="queryParams.payStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in order_stat_options"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="餐品名称" prop="comboName">
        <el-input class="form-input" v-model="queryParams.comboName" placeholder="餐品名称" />
      </el-form-item>
      <el-form-item label="餐品类别" prop="comboId">
        <el-select
          class="form-input"
          v-model="queryParams.comboId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in sortOptions"
            :key="item.goodsTypeId"
            :label="item.goodsTypeName"
            :value="item.goodsTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="餐品标签" prop="tagId">
        <el-select
          class="form-input"
          v-model="queryParams.tagId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in tagOptions"
            :key="item.tagId"
            :label="item.tagName"
            :value="item.tagId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品类型" prop="goodsType">
        <el-select
          class="form-input"
          v-model="queryParams.goodsType"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in commodityTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="下单时间" prop="timeRange">
        <el-date-picker
          style="width: 360px"
          v-model="queryParams.timeRange"
          type="datetimerange"
          :shortcuts="shortcuts"
          range-separator="~"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="userMobile">
        <el-input class="form-input" v-model="queryParams.userMobile" placeholder="手机号" />
      </el-form-item>
      <el-form-item label="城市标签" prop="cityName">
        <el-select @change="getList" v-model="queryParams.cityName" placeholder="请选择">
          <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['org:deviceOrder:export']"
          type="primary"
          :disabled="disabled"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList" @selection-change="onSelectChange">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column
        label="订单编号"
        align="center"
        prop="orderSn"
        width="170"
        fixed="left"
        sortable
      />
      <el-table-column label="支付方订单编号" width="260" align="center" prop="payTradeNo" />
      <el-table-column label="订单状态" align="center" width="100">
        <template #default="{ row }">
          <dict-tag :options="order_status" :value="row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="100" />
      <el-table-column
        label="用户名称"
        align="center"
        prop="userName"
        min-width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="城市标签" align="center" prop="cityName" />
      <el-table-column label="手机号" align="center" prop="userMobile" width="140" />
      <el-table-column label="支付时间" align="center" prop="payTime" width="100" />
      <el-table-column
        label="餐品名称"
        align="center"
        prop="comboName"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="商品类型" align="center" prop="goodsType" width="120">
        <template #default="{ row }">
          <span>{{
            commodityTypeOptions.find((item) => item.value === row.goodsType)?.label
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="amt" width="100" />
      <el-table-column label="支付方式" align="center" width="100">
        <template #default="{ row }">
          <dict-tag :options="order_paytype" :value="row.payType" />
        </template>
      </el-table-column>
      <el-table-column label="餐品类别" align="center" prop="tagName" />
      <el-table-column label="餐品标签" align="center" prop="comboTag" />
      <el-table-column label="订单类型" align="center" width="120">
        <template #default="{ row }">
          <dict-tag :options="order_origin" :value="row.orderType" />
        </template>
      </el-table-column>
      <el-table-column
        label="设备编号"
        align="center"
        prop="machineId"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="设备名称"
        align="center"
        prop="machineName"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="点位名称"
        align="center"
        prop="positionName"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template #default="{ row }">
          <el-button
            v-hasPermi="['org:deviceOrder:details']"
            link
            type="primary"
            @click="handleTableAction(row, 'detail')"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="table-bottom">
      <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
      <div class="bottom-stat">
        已选：{{ selectedObj.count }}条， 合计金额：{{ selectedObj.total?.toFixed(2) }}元
      </div>
    </div>

    <el-dialog width="500" v-model="state.visible" :close-on-click-modal="false">
      <div class="refund-dialog">
        <div>订单编号：{{ dialogObj?.orderSn }}</div>
        <div>商品名称：{{ dialogObj?.comboName }}</div>
        <div>退款金额：{{ dialogObj?.amt }}元</div>
        <el-input
          v-model="dialogFormModel.refundReason"
          type="textarea"
          placeholder="请输入退款原因"
          :autosize="{ minRows: 3, maxRows: 4 }"
          maxlength="250"
          show-word-limit
        />
        <div class="flex-center">
          <el-button type="primary" plain @click="handleAction(false)"> 取消 </el-button>
          <el-button type="primary" :loading="refunding" @click="handleAction(true)">
            确定
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="OrderList">
import useUserStore from '@/store/modules/user'
import { ElMessageBox } from 'element-plus'
import { getDeviceOrderApi, markOrder, refundOrder, getOrderRefundAmount } from '@/api/order/index'
import { getTagComboList } from '@/api/meal/comboTag'
import { onMountedOrActivated } from '@/hooks/common'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const router = useRouter()
const userStore = useUserStore()
const queryRef = ref(null)
const { proxy } = getCurrentInstance()
const { order_paytype, order_status, order_origin, order_stat_options } = proxy.useDict(
  'order_paytype',
  'order_status',
  'order_origin',
  'order_stat_options'
)
const commodityTypeOptions = [
  { label: '虚拟商品', value: 2 },
  { label: '实体商品', value: 1 }
]
const refunding = ref(false)
const tagOptions = ref([])
const sortOptions = ref([])
const tableList = ref([])
const companyOptions = computed(() => userStore.companys)
const queryParams = ref({
  type: 'normal',
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0]
})
const selectedObj = ref({
  count: 0,
  total: 0
})
const dialogObj = ref({})
const dialogFormModel = ref({})
const state = reactive({
  visible: false,
  showSearch: true,
  total: 0,
  loading: false
})

const shortcuts = [
  {
    text: '最近三天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
      return [start, end]
    }
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

function handleSearch(confirm) {
  !confirm && queryRef.value?.resetFields()

  queryParams.value.pageNum = 1
  getList()
}

function onSelectChange(arr) {
  selectedObj.value.count = arr.length
  selectedObj.value.total = arr.reduce((prev, { amt }) => prev + +amt, 0)
}

async function getList() {
  state.loading = true
  const { timeRange = [], ...data } = queryParams.value
  if (timeRange?.length) {
    data.orderTime = timeRange[0]
    data.orderEndTime = timeRange[1]
  }
  try {
    const r = await getDeviceOrderApi(data)
    tableList.value = r?.rows || []
    state.total = r?.total || 0
  } finally {
    state.loading = false
  }
}

/**table Action */
function handleTableAction(obj, operType) {
  if (operType == 'detail') {
    router.push({ path: `/order/orderDetail`, query: { id: obj?.id } })
  } else if (operType == 'refund') {
    dialogObj.value = obj
    dialogFormModel.value = {
      amt: obj.amt,
      refundReason: '',
      id: obj?.id
    }

    state.visible = true
  } else {
    ElMessageBox.prompt('确认要将此订单标识为异常单据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入异常原因',
      inputValidator: (val) => {
        if (!val) return '请输入异常原因'
        if (val.length > 250) return '异常原因不能超过250个字符'
      }
    }).then(({ value }) => {
      markOrder({ id: obj.id, exceptionReason: value }).then(() => {
        proxy.$modal.msgSuccess('操作成功')
        setTimeout(() => {
          router.push({ path: '/order/unusual' })
        }, 1000)
      })
    })
  }
}

/**dialog form */
async function handleAction(confrim) {
  if (!confrim) return (state.visible = false)

  if (!dialogFormModel.value.refundReason) {
    proxy.$modal.msgWarning('请输入退款原因')
    return
  }
  refunding.value = true
  try {
    await refundOrder(dialogFormModel.value)
    state.visible = false
    proxy.$modal.msgSuccess('操作成功')
    setTimeout(() => {
      router.push({ path: '/order/refund', query: { id: dialogFormModel.id } })
    }, 1000)
  } finally {
    refunding.value = false
  }
}

const disabled = ref(false)
function handleExport() {
  disabled.value = true
  const { timeRange = [], ...data } = queryParams.value
  if (timeRange?.length) {
    data.orderTime = timeRange[0]
    data.orderEndTime = timeRange[1]
  }
  proxy
    .download(
      '/org/orderList/exportDevOrderList',
      { ...data },
      `设备订单信息列表${new Date().getTime()}.xlsx`
    )
    .then(() => {
      disabled.value = false
    })
    .catch((err) => {
      disabled.value = false
    })
}

/**init */
function init() {
  //套餐标签
  getTagComboList({ pageNum: 1, pageSize: 1000 }).then((res) => {
    tagOptions.value = res.rows
  })
  //商品分类
  // getSortList({ pageNum: 1, pageSize: 1000 }).then((res) => {
  //   sortOptions.value = res.rows
  // })
}

/**init +  onActivated*/
init()
onMountedOrActivated(getList)
</script>

<style lang="scss" scoped>
.table-bottom {
  position: relative;
  .bottom-stat {
    position: absolute;
    top: 15px;
    left: 0;
    font-size: 14px;
    color: var(--el-pagination-text-color);
  }
}
.refund-dialog {
  line-height: 2em;
  .el-textarea {
    margin: 20px 0;
  }
}

.form-input {
  width: 210px;
}
</style>
